const Response = require('../utils/response');
const qiniu = require('qiniu');
const { createUploadToken, config } = require('../config/qiniu');
const { v4: uuidv4 } = require('uuid');
const fs = require('fs');

class UploadController {
    constructor() {
        // 在构造函数中绑定方法到实例
        this._handleUpload = this._handleUpload.bind(this);
        this.uploadFile = this.uploadFile.bind(this);
        this.uploadAvatar = this.uploadAvatar.bind(this);
        this.deleteFile = this.deleteFile.bind(this);
    }

    // 通用上传方法
    async _handleUpload(ctx, directory = '') {
        try {
            const file = ctx.request.files?.file;
            if (!file) {
                ctx.status = 400;
                ctx.body = Response.error('请选择要上传的文件');
                return;
            }

            // 获取文件名和扩展名
            const originalFilename = file.originalFilename || file.name || '';
            const ext = originalFilename.split('.').pop() || '';

            if (!ext) {
                ctx.status = 400;
                ctx.body = Response.error('无效的文件类型');
                return;
            }

            // 生成唯一的文件名
            const fileName = directory ? `${directory}/${uuidv4()}.${ext}` : `${uuidv4()}.${ext}`;

            // 读取文件内容
            const fileContent = await fs.promises.readFile(file.filepath || file.path);

            // 创建七牛云上传实例
            const uploadConfig = new qiniu.conf.Config({
                zone: config.zone,
                useHttpsDomain: config.useHttpsDomain,
                useCdnDomain: config.useCdnDomain
            });
            const formUploader = new qiniu.form_up.FormUploader(uploadConfig);
            const putExtra = new qiniu.form_up.PutExtra();

            // 上传文件
            const uploadToken = createUploadToken();
            const result = await new Promise((resolve, reject) => {
                formUploader.put(
                    uploadToken,
                    fileName,
                    fileContent,
                    putExtra,
                    (err, body, info) => {
                        if (err) {
                            reject(err);
                            return;
                        }
                        if (info.statusCode === 200) {
                            resolve(body);
                        } else {
                            reject(new Error('上传失败'));
                        }
                    }
                );
            });

            // 清理临时文件
            if (file.filepath || file.path) {
                await fs.promises.unlink(file.filepath || file.path);
            }

            // 返回文件访问链接
            const fileUrl = `${config.domain}${result.key}`;
            return {
                url: fileUrl,
                key: result.key,
                name: originalFilename,
                size: file.size
            };
        } catch (error) {
            console.error('文件处理失败:', error);
            throw error;
        }
    }

    // 需要验证的文件上传
    async uploadFile(ctx) {
        try {
            const result = await this._handleUpload(ctx, 'files');
            ctx.body = Response.success(result);
        } catch (error) {
            console.error('文件上传失败:', error);
            ctx.status = 500;
            ctx.body = Response.error('文件上传失败：' + error.message);
        }
    }

    // 头像上传（不需要验证）
    async uploadAvatar(ctx) {
        try {
            const result = await this._handleUpload(ctx, 'avatars');
            ctx.body = Response.success(result);
        } catch (error) {
            console.error('头像上传失败:', error);
            ctx.status = 500;
            ctx.body = Response.error('头像上传失败：' + error.message);
        }
    }

    // 删除文件（根据路径判断是否需要验证）
    async deleteFile(ctx) {
        try {
            const { key } = ctx.params;
            if (!key) {
                ctx.status = 400;
                ctx.body = Response.error('请提供要删除的文件key');
                return;
            }
 
            
            // 创建七牛云管理实例
            const mac = new qiniu.auth.digest.Mac(config.accessKey, config.secretKey);
            const bucketManager = new qiniu.rs.BucketManager(mac, new qiniu.conf.Config());

            // 删除文件
            const result = await new Promise((resolve, reject) => {
                bucketManager.delete(config.bucket, key, (err, respBody, respInfo) => {
                    if (err) {
                        reject(err);
                        return;
                    }
                    if (respInfo.statusCode === 200) {
                        resolve(respBody);
                    } else {
                        reject(new Error('删除失败'));
                    }
                });
            });

            ctx.body = Response.success(null, '文��删除成功');

        } catch (error) {
            console.error('文件删除失败:', error);
            ctx.status = 500;
            ctx.body = Response.error('文件删除失败：' + error.message);
        }
    }

    // 删除头像（无需验证）
    async deleteAvatar(ctx) {
        try {
            const { fileUrl } = ctx.request.body;
            if (!fileUrl) {
                ctx.status = 400;
                ctx.body = Response.error('请提供文件地址');
                return;
            }

            // 从URL中提取key
            let key = '';
            try {
                // 处理完整URL
                if (fileUrl.startsWith('http')) {
                    const url = new URL(fileUrl);
                    key = url.pathname.substring(1); // 移除开头的斜杠
                } else {
                    key = fileUrl;
                }
            } catch (error) {
                ctx.status = 400;
                ctx.body = Response.error('无效的文件地址');
                return;
            }

            // 验证是否是头像文件
            if (!key.startsWith('avatars/')) {
                ctx.status = 400;
                ctx.body = Response.error('无效的头像文件');
                return;
            }

            // 创建七牛云管理实例
            const mac = new qiniu.auth.digest.Mac(config.accessKey, config.secretKey);
            const bucketManager = new qiniu.rs.BucketManager(mac, new qiniu.conf.Config());

            // 删除文件
            const result = await new Promise((resolve, reject) => {
                bucketManager.delete(config.bucket, key, (err, respBody, respInfo) => {
                    if (err) {
                        reject(err);
                        return;
                    }
                    if (respInfo.statusCode === 200) {
                        resolve(respBody);
                    } else {
                        reject(new Error('删除失败'));
                    }
                });
            });

            ctx.body = Response.success(null, '头像删除成功');

        } catch (error) {
            ctx.status = 500;
            ctx.body = Response.error(error.message);
        }
    }
}

module.exports = new UploadController(); 